using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 焦点处理器
    /// 负责从记忆中提取和生成反思焦点点
    /// </summary>
    public class FocalPointProcessor
    {
        private Dictionary<string, float> focusWeights;
        private List<string> focusTemplates;
        private HashSet<string> importantKeywords;
        
        public FocalPointProcessor()
        {
            InitializeProcessor();
        }
        
        /// <summary>
        /// 初始化焦点处理器
        /// </summary>
        private void InitializeProcessor()
        {
            // 初始化焦点权重
            focusWeights = new Dictionary<string, float>
            {
                // 社交关系权重
                ["relationship"] = 1.5f,
                ["friend"] = 1.4f,
                ["conversation"] = 1.2f,
                ["social"] = 1.3f,
                ["meeting"] = 1.1f,
                
                // 情感和心理权重
                ["feeling"] = 1.4f,
                ["emotion"] = 1.3f,
                ["happy"] = 1.2f,
                ["sad"] = 1.2f,
                ["angry"] = 1.3f,
                ["excited"] = 1.1f,
                ["worried"] = 1.2f,
                
                // 目标和成就权重
                ["goal"] = 1.5f,
                ["achievement"] = 1.4f,
                ["success"] = 1.3f,
                ["failure"] = 1.4f,
                ["progress"] = 1.2f,
                ["challenge"] = 1.3f,
                
                // 日常活动权重
                ["work"] = 1.1f,
                ["routine"] = 1.0f,
                ["habit"] = 1.1f,
                ["schedule"] = 1.0f,
                
                // 学习和成长权重
                ["learning"] = 1.3f,
                ["discovery"] = 1.4f,
                ["insight"] = 1.5f,
                ["understanding"] = 1.3f,
                ["realization"] = 1.4f,
                
                // 冲突和问题权重
                ["conflict"] = 1.6f,
                ["problem"] = 1.5f,
                ["difficulty"] = 1.4f,
                ["mistake"] = 1.3f,
                ["confusion"] = 1.2f
            };
            
            // 初始化焦点模板
            focusTemplates = new List<string>
            {
                "Recent interactions with {person}",
                "My feelings about {topic}",
                "Progress towards {goal}",
                "Patterns in my {behavior}",
                "Relationships with {people}",
                "Experiences at {location}",
                "Thoughts about {subject}",
                "Changes in my {aspect}",
                "Challenges with {situation}",
                "Understanding of {concept}"
            };
            
            // 重要关键词集合
            importantKeywords = new HashSet<string>
            {
                "important", "significant", "meaningful", "crucial", "vital", "critical",
                "memorable", "impactful", "transformative", "life-changing", "profound",
                "surprising", "unexpected", "shocking", "amazing", "wonderful",
                "terrible", "awful", "devastating", "heartbreaking", "joyful"
            };
        }
        
        /// <summary>
        /// 生成反思焦点点
        /// </summary>
        public List<string> GenerateFocusPoints(List<MemoryNode> memories, int maxFocusPoints)
        {
            try
            {
                var focusPoints = new List<string>();
                
                // 1. 基于高重要性记忆生成焦点
                var highImportancePoints = GenerateHighImportanceFoci(memories);
                focusPoints.AddRange(highImportancePoints);
                
                // 2. 基于频繁主题生成焦点
                var thematicPoints = GenerateThematicFoci(memories);
                focusPoints.AddRange(thematicPoints);
                
                // 3. 基于社交关系生成焦点
                var socialPoints = GenerateSocialFoci(memories);
                focusPoints.AddRange(socialPoints);
                
                // 4. 基于情感模式生成焦点
                var emotionalPoints = GenerateEmotionalFoci(memories);
                focusPoints.AddRange(emotionalPoints);
                
                // 5. 基于时间模式生成焦点
                var temporalPoints = GenerateTemporalFoci(memories);
                focusPoints.AddRange(temporalPoints);
                
                // 去重并按重要性排序
                var uniqueFocusPoints = focusPoints.Distinct().ToList();
                var rankedFocusPoints = RankFocusPoints(uniqueFocusPoints, memories);
                
                return rankedFocusPoints.Take(maxFocusPoints).ToList();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error generating focus points: {ex.Message}");
                return new List<string> { "recent experiences", "important events", "relationships" };
            }
        }
        
        /// <summary>
        /// 基于高重要性记忆生成焦点
        /// </summary>
        private List<string> GenerateHighImportanceFoci(List<MemoryNode> memories)
        {
            var foci = new List<string>();
            
            var highImportanceMemories = memories.Where(m => m.poignancy >= 7).ToList();
            
            foreach (var memory in highImportanceMemories.Take(5))
            {
                // 从高重要性记忆中提取主题
                var themes = ExtractThemesFromMemory(memory);
                foreach (var theme in themes.Take(2)) // 每个记忆最多提取2个主题
                {
                    if (!string.IsNullOrEmpty(theme))
                    {
                        foci.Add($"Significant experiences with {theme}");
                    }
                }
                
                // 如果有参与者，生成人际关系焦点
                if (memory.participants != null && memory.participants.Count > 0)
                {
                    var mainParticipant = memory.participants.First();
                    foci.Add($"Important interactions with {mainParticipant}");
                }
            }
            
            return foci;
        }
        
        /// <summary>
        /// 基于频繁主题生成焦点
        /// </summary>
        private List<string> GenerateThematicFoci(List<MemoryNode> memories)
        {
            var foci = new List<string>();
            
            try
            {
                // 统计关键词频率
                var keywordFrequency = new Dictionary<string, int>();
                
                foreach (var memory in memories)
                {
                    if (memory.keywords != null)
                    {
                        foreach (var keyword in memory.keywords)
                        {
                            var lowerKeyword = keyword.ToLower();
                            keywordFrequency[lowerKeyword] = keywordFrequency.GetValueOrDefault(lowerKeyword, 0) + 1;
                        }
                    }
                }
                
                // 找出频繁出现的重要主题
                var frequentThemes = keywordFrequency
                    .Where(kv => kv.Value >= 3 && focusWeights.ContainsKey(kv.Key)) // 至少出现3次且是重要关键词
                    .OrderByDescending(kv => kv.Value * focusWeights.GetValueOrDefault(kv.Key, 1f))
                    .Take(3)
                    .Select(kv => kv.Key);
                
                foreach (var theme in frequentThemes)
                {
                    foci.Add($"Recurring patterns involving {theme}");
                }
                
                // 分析主题组合
                var themeGroups = AnalyzeThemeGroups(keywordFrequency);
                foreach (var group in themeGroups.Take(2))
                {
                    foci.Add($"Connection between {string.Join(" and ", group)}");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error generating thematic foci: {ex.Message}");
            }
            
            return foci;
        }
        
        /// <summary>
        /// 基于社交关系生成焦点
        /// </summary>
        private List<string> GenerateSocialFoci(List<MemoryNode> memories)
        {
            var foci = new List<string>();
            
            try
            {
                // 统计参与者出现频率
                var participantFrequency = new Dictionary<string, int>();
                var participantImportance = new Dictionary<string, float>();
                
                foreach (var memory in memories)
                {
                    if (memory.participants != null)
                    {
                        foreach (var participant in memory.participants)
                        {
                            if (!string.IsNullOrEmpty(participant))
                            {
                                participantFrequency[participant] = participantFrequency.GetValueOrDefault(participant, 0) + 1;
                                participantImportance[participant] = participantImportance.GetValueOrDefault(participant, 0f) + memory.poignancy;
                            }
                        }
                    }
                }
                
                // 找出重要的社交对象
                var importantPeople = participantFrequency
                    .Where(kv => kv.Value >= 2) // 至少出现2次
                    .OrderByDescending(kv => participantImportance.GetValueOrDefault(kv.Key, 0f) / kv.Value) // 按平均重要性排序
                    .Take(3)
                    .Select(kv => kv.Key);
                
                foreach (var person in importantPeople)
                {
                    foci.Add($"My evolving relationship with {person}");
                }
                
                // 分析社交模式
                var socialPatterns = AnalyzeSocialPatterns(memories);
                foci.AddRange(socialPatterns);
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error generating social foci: {ex.Message}");
            }
            
            return foci;
        }
        
        /// <summary>
        /// 基于情感模式生成焦点
        /// </summary>
        private List<string> GenerateEmotionalFoci(List<MemoryNode> memories)
        {
            var foci = new List<string>();
            
            try
            {
                // 情感关键词映射
                var emotionKeywords = new Dictionary<string, string>
                {
                    ["happy"] = "happiness", ["joy"] = "joy", ["excited"] = "excitement",
                    ["sad"] = "sadness", ["disappointed"] = "disappointment", ["frustrated"] = "frustration",
                    ["angry"] = "anger", ["annoyed"] = "irritation", ["furious"] = "rage",
                    ["worried"] = "worry", ["anxious"] = "anxiety", ["nervous"] = "nervousness",
                    ["proud"] = "pride", ["accomplished"] = "accomplishment", ["satisfied"] = "satisfaction",
                    ["confused"] = "confusion", ["surprised"] = "surprise", ["shocked"] = "shock"
                };
                
                // 统计情感模式
                var emotionFrequency = new Dictionary<string, int>();
                var emotionContexts = new Dictionary<string, List<string>>();
                
                foreach (var memory in memories)
                {
                    if (memory.keywords != null)
                    {
                        foreach (var keyword in memory.keywords)
                        {
                            if (emotionKeywords.ContainsKey(keyword.ToLower()))
                            {
                                var emotion = emotionKeywords[keyword.ToLower()];
                                emotionFrequency[emotion] = emotionFrequency.GetValueOrDefault(emotion, 0) + 1;
                                
                                if (!emotionContexts.ContainsKey(emotion))
                                {
                                    emotionContexts[emotion] = new List<string>();
                                }
                                
                                // 添加上下文信息
                                if (!string.IsNullOrEmpty(memory.locationName))
                                {
                                    emotionContexts[emotion].Add(memory.locationName);
                                }
                            }
                        }
                    }
                }
                
                // 生成情感焦点
                var frequentEmotions = emotionFrequency
                    .Where(kv => kv.Value >= 2)
                    .OrderByDescending(kv => kv.Value)
                    .Take(2);
                
                foreach (var emotion in frequentEmotions)
                {
                    var contexts = emotionContexts.GetValueOrDefault(emotion.Key, new List<string>());
                    var commonContext = contexts.GroupBy(c => c).OrderByDescending(g => g.Count()).FirstOrDefault()?.Key;
                    
                    if (!string.IsNullOrEmpty(commonContext))
                    {
                        foci.Add($"My feelings of {emotion.Key} in {commonContext}");
                    }
                    else
                    {
                        foci.Add($"Patterns in my experience of {emotion.Key}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error generating emotional foci: {ex.Message}");
            }
            
            return foci;
        }
        
        /// <summary>
        /// 基于时间模式生成焦点
        /// </summary>
        private List<string> GenerateTemporalFoci(List<MemoryNode> memories)
        {
            var foci = new List<string>();
            
            try
            {
                // 分析时间段模式
                var timePatterns = new Dictionary<string, int>();
                
                foreach (var memory in memories)
                {
                    var hour = memory.createdTime.Hour;
                    string timeOfDay;
                    
                    if (hour >= 6 && hour < 12)
                        timeOfDay = "morning";
                    else if (hour >= 12 && hour < 18)
                        timeOfDay = "afternoon";
                    else if (hour >= 18 && hour < 22)
                        timeOfDay = "evening";
                    else
                        timeOfDay = "night";
                    
                    timePatterns[timeOfDay] = timePatterns.GetValueOrDefault(timeOfDay, 0) + 1;
                }
                
                // 找出活跃的时间段
                var activeTimeOfDay = timePatterns.OrderByDescending(kv => kv.Value).FirstOrDefault();
                if (activeTimeOfDay.Value >= 3)
                {
                    foci.Add($"My {activeTimeOfDay.Key} experiences and routines");
                }
                
                // 分析最近vs较早的记忆模式
                var recent = memories.Count(m => (DateTime.Now - m.createdTime).TotalHours <= 24);
                var older = memories.Count - recent;
                
                if (recent >= older && recent >= 3)
                {
                    foci.Add("Recent changes in my daily life");
                }
                else if (older > recent && older >= 5)
                {
                    foci.Add("Long-term patterns in my behavior");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error generating temporal foci: {ex.Message}");
            }
            
            return foci;
        }
        
        /// <summary>
        /// 从记忆中提取主题
        /// </summary>
        private List<string> ExtractThemesFromMemory(MemoryNode memory)
        {
            var themes = new List<string>();
            
            try
            {
                // 从关键词中提取主题
                if (memory.keywords != null)
                {
                    var importantKeywords = memory.keywords
                        .Where(k => focusWeights.ContainsKey(k.ToLower()) || importantKeywords.Contains(k.ToLower()))
                        .Take(3);
                    
                    themes.AddRange(importantKeywords);
                }
                
                // 从内容中提取名词短语（简化实现）
                if (!string.IsNullOrEmpty(memory.content))
                {
                    var words = memory.content.Split(' ');
                    for (int i = 0; i < words.Length - 1; i++)
                    {
                        var phrase = $"{words[i]} {words[i + 1]}";
                        if (IsImportantPhrase(phrase))
                        {
                            themes.Add(phrase);
                        }
                    }
                }
                
                // 从参与者中提取
                if (memory.participants != null)
                {
                    themes.AddRange(memory.participants.Take(2));
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error extracting themes from memory: {ex.Message}");
            }
            
            return themes.Distinct().ToList();
        }
        
        /// <summary>
        /// 分析主题组合
        /// </summary>
        private List<List<string>> AnalyzeThemeGroups(Dictionary<string, int> keywordFrequency)
        {
            var groups = new List<List<string>>();
            
            try
            {
                var frequentKeywords = keywordFrequency
                    .Where(kv => kv.Value >= 2)
                    .Select(kv => kv.Key)
                    .ToList();
                
                // 简单的主题组合检测
                var socialGroup = frequentKeywords.Where(k => 
                    k.Contains("friend") || k.Contains("social") || k.Contains("conversation") || k.Contains("relationship"))
                    .ToList();
                
                if (socialGroup.Count >= 2)
                {
                    groups.Add(socialGroup.Take(3).ToList());
                }
                
                var emotionalGroup = frequentKeywords.Where(k => 
                    k.Contains("happy") || k.Contains("sad") || k.Contains("feeling") || k.Contains("emotion"))
                    .ToList();
                
                if (emotionalGroup.Count >= 2)
                {
                    groups.Add(emotionalGroup.Take(3).ToList());
                }
                
                var workGroup = frequentKeywords.Where(k => 
                    k.Contains("work") || k.Contains("goal") || k.Contains("task") || k.Contains("achievement"))
                    .ToList();
                
                if (workGroup.Count >= 2)
                {
                    groups.Add(workGroup.Take(3).ToList());
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error analyzing theme groups: {ex.Message}");
            }
            
            return groups;
        }
        
        /// <summary>
        /// 分析社交模式
        /// </summary>
        private List<string> AnalyzeSocialPatterns(List<MemoryNode> memories)
        {
            var patterns = new List<string>();
            
            try
            {
                var socialMemories = memories.Where(m => 
                    m.type == MemoryType.Chat || 
                    (m.participants != null && m.participants.Count > 1)).ToList();
                
                if (socialMemories.Count >= 5)
                {
                    patterns.Add("Patterns in my social interactions");
                }
                
                // 检查群体vs一对一互动
                var groupInteractions = socialMemories.Count(m => m.participants != null && m.participants.Count > 2);
                var oneOnOneInteractions = socialMemories.Count(m => m.participants != null && m.participants.Count == 2);
                
                if (groupInteractions >= 3)
                {
                    patterns.Add("My experience in group settings");
                }
                
                if (oneOnOneInteractions >= 3)
                {
                    patterns.Add("My one-on-one relationship dynamics");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error analyzing social patterns: {ex.Message}");
            }
            
            return patterns;
        }
        
        /// <summary>
        /// 对焦点点进行排序
        /// </summary>
        private List<string> RankFocusPoints(List<string> focusPoints, List<MemoryNode> memories)
        {
            try
            {
                var rankedPoints = new List<(string focus, float score)>();
                
                foreach (var focus in focusPoints)
                {
                    var score = CalculateFocusScore(focus, memories);
                    rankedPoints.Add((focus, score));
                }
                
                return rankedPoints
                    .OrderByDescending(x => x.score)
                    .Select(x => x.focus)
                    .ToList();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error ranking focus points: {ex.Message}");
                return focusPoints;
            }
        }
        
        /// <summary>
        /// 计算焦点分数
        /// </summary>
        private float CalculateFocusScore(string focus, List<MemoryNode> memories)
        {
            float score = 1f;
            
            try
            {
                var lowerFocus = focus.ToLower();
                
                // 基于关键词权重
                foreach (var keyword in focusWeights.Keys)
                {
                    if (lowerFocus.Contains(keyword))
                    {
                        score += focusWeights[keyword];
                    }
                }
                
                // 基于相关记忆数量
                var relatedMemories = memories.Count(m => 
                    m.content.Contains(focus, StringComparison.OrdinalIgnoreCase) ||
                    (m.keywords != null && m.keywords.Any(k => focus.Contains(k, StringComparison.OrdinalIgnoreCase))));
                
                score += relatedMemories * 0.2f;
                
                // 基于相关记忆的平均重要性
                var relevantMemories = memories.Where(m => 
                    m.content.Contains(focus, StringComparison.OrdinalIgnoreCase) ||
                    (m.keywords != null && m.keywords.Any(k => focus.Contains(k, StringComparison.OrdinalIgnoreCase)))).ToList();
                
                if (relevantMemories.Count > 0)
                {
                    var avgImportance = relevantMemories.Average(m => m.poignancy);
                    score += avgImportance * 0.1f;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[FocalPointProcessor] Error calculating focus score: {ex.Message}");
            }
            
            return score;
        }
        
        /// <summary>
        /// 检查是否为重要短语
        /// </summary>
        private bool IsImportantPhrase(string phrase)
        {
            var lowerPhrase = phrase.ToLower();
            var importantPhrases = new HashSet<string>
            {
                "social interaction", "personal goal", "important decision", "significant event",
                "emotional response", "relationship change", "new experience", "major challenge",
                "learning opportunity", "meaningful conversation", "personal growth", "life change"
            };
            
            return importantPhrases.Any(ip => lowerPhrase.Contains(ip));
        }
        
        /// <summary>
        /// 设置焦点权重
        /// </summary>
        public void SetFocusWeight(string keyword, float weight)
        {
            focusWeights[keyword.ToLower()] = weight;
        }
        
        /// <summary>
        /// 获取焦点统计信息
        /// </summary>
        public string GetFocusStats()
        {
            return $"Focus weights configured: {focusWeights.Count}, Templates available: {focusTemplates.Count}";
        }
    }
}